<template>
  <div class="vue-container">
    <el-row :gutter="24">
      <el-col :span="4" class="left y-card" :style="{'height': (height + 80) + 'px'}">
        <el-select
          v-model="filterText"
          style="margin-top: 6px;"
          filterable
          clearable
          remote
          reserve-keyword
          placeholder="输入关键词搜索"
          :remote-method="searchDept"
          :loading="treeLoading"
          @change="deptChange"
        >
          <el-option
            v-for="item in treeList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-tree
          ref="tree"
          class="filter-tree"
          node-key="id"
          :default-expanded-keys="expandedKeys"
          lazy
          :expand-on-click-node="false"
          highlight-current
          :load="loadNode"
          :data="deptData"
          :props="defaultProps"
          @node-click="nodeClick"
        />
      </el-col>
      <el-col :span="20">
        <common-form
          ref="commonForm"
          :disabled="disabled"
          :options="options"
          @handlerClick="handlerClick"
          @advancedSearch="handlerQuery"
        >
          <template slot="advanced-content">
            <el-form ref="advancedForm" style="margin-top: 20px;" :model="queryForm" label-width="80px">
              <el-form-item label="用户账号">
                <el-input v-model="queryForm.username" placeholder="请输入用户账号" />
              </el-form-item>
              <el-form-item label="昵称">
                <el-input v-model="queryForm.name" placeholder="请输入昵称" />
              </el-form-item>
              <el-form-item label="性别">
                <el-select
                  v-model="queryForm.sex"
                  style="width: 100%;"
                  clearable
                  placeholder="请选择性别"
                >
                  <el-option
                    v-for="(item, index) in sexList"
                    :key="index"
                    :label="item.label"
                    :value="Number(item.code)"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="账号状态">
                <el-select
                  v-model="queryForm.status"
                  style="width: 100%;"
                  clearable
                  placeholder="请选择账号状态"
                >
                  <el-option
                    v-for="(item, index) in statusList"
                    :key="index"
                    :label="item.label"
                    :value="Number(item.code)"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="创建时间">
                <el-date-picker
                  v-model="queryForm.createTime"
                  style="width: 100%;"
                  type="datetimerange"
                  placeholder="选择时间"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                />
              </el-form-item>
            </el-form>
          </template>
        </common-form>
        <common-table
          :table-data="data"
          :columns="columns"
          :height="height"
          :current-page="queryForm.pageNum"
          :page-size="queryForm.pageSize"
          :total="totalPage"
          :loading="loading"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange"
          @handleSelectionChange="handleSelectionChange"
        >
          <!-- 列表序号 -->
          <template #serialNumber="scope">
            <span>{{
              Number(scope.index + 1) + (queryForm.pageNum - 1) * queryForm.pageSize
            }}</span>
          </template>
          <!-- 用户头像 -->
          <template #avatar="scope">
            <el-avatar v-if="scope.row.avatar" :src="getImageUrl(scope.row.avatar)" />
            <el-avatar v-else>{{ scope.row.name }}</el-avatar>
          </template>
          <!-- 用户性别 -->
          <template #sex="scope">
            <template v-for="(item, index) in sexList">
              <el-tag
                v-if="scope.row.sex == item.code"
                :key="index"
                :type="scope.row.sex == 0 ? 'info' : scope.row.sex == 2 ? 'danger' : ''"
              >{{ item.label }}</el-tag>
            </template>
          </template>
          <!-- 账号状态 -->
          <template #status="scope">
            <el-popconfirm
              v-permission="{ permission: 'system:admin:user:update', disabled }"
              :title="scope.row.status === 1 ? '确定要禁用该账号吗？' : '确定要启用该账号吗？'"
              icon=""
              @confirm="popConfirm(scope.row)"
            >
              <el-switch
                slot="reference"
                v-model="scope.row.status"
                v-permission="{ permission: 'system:admin:user:update', disabled }"
                :active-value="1"
                :inactive-value="2"
                @change="switchChange($event, scope.row)"
              />
            </el-popconfirm>
          </template>
          <template #createTime="scope">
            {{ scope.row.createTime | formatTime }}
          </template>
          <!-- 列表操作按钮-->
          <template #operation="scope">
            <el-button
              v-throttle
              v-permission="'system:admin:user:update'"
              :size="size"
              type="text"
              icon="el-icon-edit-outline"
              @click.stop="handlerSave(scope.row)"
            >编辑</el-button>
            <el-button
              v-throttle
              v-permission="'system:admin:user:del'"
              :size="size"
              type="text"
              icon="el-icon-delete"
              class="danger-btn"
              @click.stop="handlerDel(funs['del'], scope.row)"
            >删除</el-button>
            <el-dropdown style="margin-left: 10px;">
              <el-button
                v-permission="'system:admin:user:update'"
                :size="size"
                type="text"
              >更多<i class="el-icon--right el-icon-more" /></el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <el-button
                    v-throttle
                    v-permission="'system:admin:user:reset:password'"
                    :size="size"
                    type="text"
                    icon="el-icon-refresh"
                    @click.stop="handlerResetPassword(scope.row)"
                  >重置密码</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button
                    v-throttle
                    v-permission="'ops:blacklist:create'"
                    :size="size"
                    type="text"
                    icon="el-icon-circle-plus"
                    @click.stop="handlerAddToBlacklist(scope.row)"
                  >加入黑名单</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </common-table>
      </el-col>
    </el-row>
    <!-- 新增or编辑组件 -->
    <add-or-update ref="addOrUpdate" :obj="{ sexList, statusList }" @ok="getList" />
    <!-- 全局导入组件 -->
    <to-channel ref="toChannel" title="用户导入" @change="getList" />
    <!--重置密码组件-->
    <reset-password ref="resetPassword" />
    <!--加入黑名单组件-->
    <add-to-blacklist ref="addToBlacklist" />
  </div>
</template>
<script>
import { mixin } from '@/views/pages/mixin'
import { list as tree } from '@/api/system/department'
import AddOrUpdate from './components/save'
import ResetPassword from './components/reset-password'
import AddToBlacklist from '@/components/AddToBlacklist'
export default {
  name: 'User',
  components: {
    ResetPassword,
    AddOrUpdate,
    AddToBlacklist
  },
  mixins: [mixin],
  data() {
    return {
      treeLoading: false, // 树搜索loading
      // 部门关键字筛选
      filterText: '',
      treeList: [], // 树列表
      expandedKeys: [], // 默认展开的key数组
      // 部门树配置项
      defaultProps: {
        children: 'children',
        label: 'name',
        isLeaf: 'isLeaf'
      },
      // 部门树懒加载
      deptData: [],
      sexList: [], // 性别数组
      statusList: [], // 状态数组
      // 表头数组
      columns: [
        {
          type: 'selection',
          width: '60'
        },
        {
          prop: 'number',
          label: '序号',
          width: '70',
          type: 'slot',
          slotType: 'serialNumber'
        },
        {
          prop: 'avatar',
          label: '头像',
          type: 'slot',
          slotType: 'avatar'
        },
        {
          prop: 'username',
          width: '120',
          label: '用户账号'
        },
        {
          prop: 'name',
          label: '昵称'
        },
        {
          prop: 'mobile',
          label: '手机号码',
          width: '120',
          align: 'center'
        },
        {
          prop: 'email',
          label: '邮箱',
          width: '140',
          align: 'center'
        },
        {
          prop: 'sex',
          label: '用户性别',
          type: 'slot',
          slotType: 'sex'
        },
        {
          prop: 'status',
          label: '账号状态',
          type: 'slot',
          slotType: 'status'
        },
        {
          prop: 'createTime',
          type: 'slot',
          width: '140',
          slotType: 'createTime',
          label: '创建时间'
        },
        {
          type: 'slot',
          prop: 'operation',
          label: '操作',
          width: '200',
          slotType: 'operation',
          align: 'center',
          fixed: 'right'
        }
      ]
    }
  },
  async created() {
    // 通过全局方法取数据字典
    this.sexList = await this.getDictInfo('dict_sex')
    this.statusList = await this.getDictInfo('dict_status')
  },
  methods: {
    // 打开保存弹窗
    handlerSave(item) {
      if (!item) {
        item = {
          departmentId: this.queryForm.departmentId,
          departmentName: this.queryForm.departmentName
        }
      }
      this.$refs.addOrUpdate.openDialog(item)
    },
    // 树搜索
    searchDept(keyword) {
      if (keyword !== '') {
        const params = {
          keyword: keyword
        }
        this.treeLoading = true
        tree(params).then(res => {
          this.treeList = res.data
        }).finally(() => {
          this.treeLoading = false
        })
      }
    },
    // 点击树搜索到的节点
    deptChange(id) {
      const params = { parentId: '0' }
      if (id) {
        delete params.parentId
        params.id = id
      } else {
        this.handlerReset()
      }
      tree(params).then(res => {
        this.deptData = res.data
        if (res.data && res.data.length > 0) {
          this.expandedKeys = [res.data[0].id]
        }
      })
    },
    // 懒加载部门树
    loadNode(node, resolve) {
      const params = { parentId: '0' }
      if (node.data.id) {
        params.parentId = node.data.id
      }
      tree(params).then(res => {
        resolve(res.data)
        if (!node.data.id && res.data.length > 0) {
          this.expandedKeys = [res.data[0].id]
        }
      })
    },
    // 账号状态切换触发
    switchChange(e, form) {
      form.status = e === 1 ? 2 : 1
    },
    // 确认禁用或启用
    popConfirm(form) {
      this.loading = true
      form.status = form.status === 1 ? 2 : 1
      form.isStatusChange = true
      this.funs['edit'](form).then(() => {
        if (form.status === 1) {
          this.$message.success('账号已启用')
        } else {
          this.$message.error('账号已禁用')
        }
      }).catch(e => {
        form.status = form.status === 1 ? 2 : 1
      }).finally(() => {
        this.loading = false
      })
    },
    // 打开重置密码弹窗
    handlerResetPassword(item) {
      this.$refs.resetPassword.openDialog(item)
    },
    // 打开加入黑名单弹窗
    handlerAddToBlacklist(item) {
      const row = {
        disabledType: true,
        disabledData: true,
        sourceType: 1,
        type: 1,
        username: item.username
      }
      this.$refs.addToBlacklist.openDialog(row)
    },
    // 重置搜索
    handlerReset() {
      this.options.find((item) => item.type === 'search').bindValue = ''
      this.queryForm = {
        pageNum: 1,
        pageSize: this.queryForm.pageSize
      }
      this.$refs.tree.setCurrentKey(null)
      this.getList()
    },
    // 部门筛选
    nodeClick(data) {
      this.queryForm.departmentId = data.id
      this.queryForm.departmentName = data.name
      this.getList()
    }
  }
}
</script>

<style scoped>

.left {
  overflow: auto;
}
.filter-tree {
  width: 100%;
  margin-top: 6px;
  display: inline-block;
  white-space: nowrap;
}
</style>
